/**
 *@File signal.c
 *
 *@Author: Bob
 *
 *@Create Time: 2017-03-09 15:39:33
 *
 *@Last Modify: Bob
 *
 *@Last Modify Time: 2016-12-2 17:39:33
 *
 *@Description:
 *   Linux/Unix系统下处理kill信号(SIGKILL)时,让程序exit gracefully	
 *	参见博客：http://blog.csdn.net/slvher/article/details/8977338
 */

#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>


volatile sig_atomic_t g_done = 0;


void SignalHandler(int signumber)
{
	g_done = 1;
}


int main(int argc, char *argv[])
{
	struct sigaction action;
	memset(&action, 0, sizeof(struct sigaction));
	
	action.sa_handler = SignalHandler;
	sigaction(SIGTERM, &action, NULL);
	int loop = 0;
	int t = 0;
	
	while(!g_done)
	{
		t = sleep(3);
		while(t > 0)
		{
			printf("[%s:%s:%d]Loop run was interrupted with:%d second to go, finishing...\n", __FILE__, __FUNCTION__, __LINE__, t);
			t = sleep(t);
		}

		printf("[%s:%s:%d]Finished loop run:%d\n", __FILE__, __FUNCTION__, __LINE__, loop++);
	}

	printf("[%s:%s:%d]g_done!\n", __FILE__, __FUNCTION__, __LINE__);
	return 0;
}
